package com.zou.controller;

import com.zou.bean.CarInfo;
import com.zou.service.CarInfoService;
import com.zou.service.ClientService;
import com.zou.utils.TableConvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/** 汽车表控制层 */
@Controller
@RequestMapping("/car")
public class CarController {

  // 创建汽车业务层对象
  @Autowired private CarInfoService carService;

  // 创建客户服务层对象
  @Autowired private ClientService cliService;

  /**
   * 更新
   *
   * @param id
   * @param
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/{id}", method = RequestMethod.POST)
  public String putResource(@PathVariable int id, @RequestBody CarInfo car) {

    // 设置汽车Id
    car.setCarId(id);

    // 设置客户Id
    car.setClientId(cliService.selectId(car.getClientName()));

    // 调用更新方法
    carService.updateByPrimaryKeySelective(car);

    // 返回success
    return "success";
  }

  /**
   * 更新前跳转页面
   *
   * @param id
   * @return
   */
  @RequestMapping(value = "/jump/{id}", method = RequestMethod.POST)
  public ModelAndView jump(
      @PathVariable int id, String carBrand, String carNumber, String clientName) {

    // 跳转至更新页面，并传递数据
    return new ModelAndView("forward:/views-add/car-add.jsp")
        .addObject("car", new CarInfo(id, carBrand, carNumber, clientName));
  }

  /** 新增 */
  @ResponseBody
  @RequestMapping(value = "/", method = RequestMethod.POST)
  public String add(@RequestBody CarInfo car) {

    //    int i = 1 / 0;
    // 设置客户Id
    car.setClientId(cliService.selectId(car.getClientName()));

    // 插入汽车信息
    carService.insertSelective(car);

    // 返回success
    return "success";
  }

  /** 删除 */
  @ResponseBody
  @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  public String delete(@PathVariable int id) {

    // 删除
    carService.deleteByPrimaryKey(id);

    // 返回success
    return "success";
  }

  /**
   * 查询所有汽车信息
   *
   * @return
   */
  @RequestMapping(value = "/", method = RequestMethod.GET)
  @ResponseBody
  public List<CarInfo> selectAll() {
    return carService.selectAll();
  }

  /**
   * 查询所有汽车信息(layui渲染)
   *
   * @return
   */
  @RequestMapping(value = "/2", method = RequestMethod.GET)
  @ResponseBody
  public Map selectAll2() {

    // 调用方法渲染
    return TableConvent.toDo(carService.selectAll());
  }
}
